package com.taotao.web.controller;

import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.common.pojo.CommonResult;
import com.taotao.web.pojo.Cart;
import com.taotao.web.pojo.ItemVO;
import com.taotao.web.pojo.Order;
import com.taotao.web.pojo.User;
import com.taotao.web.service.CartService;
import com.taotao.web.service.ItemService;
import com.taotao.web.service.OrderService;
import com.taotao.web.threadlocal.UserThreadLocal;

@Controller
@RequestMapping("order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private CartService cartService;
	
	@GetMapping("{itemId}")
	public String toOrder(@PathVariable("itemId")Long itemId, Model model){
		
		// 查询商品详情
		ItemVO itemVO = this.itemService.queryItemById(itemId);
		// 绑定到页面jsp
		model.addAttribute("item", itemVO);
		// 返回到订单确认页
		return "order";
	}
	
	/**
	 * 创建订单
	 * @param order
	 * @return
	 */
	@PostMapping("submit")
	public ResponseEntity<CommonResult> orderSubmit(Order order, @CookieValue("TT_TOKEN")String token){
		
		try {
			// 获取用户信息
			User user = UserThreadLocal.get();
			// 给订单设置买家信息
			order.setUserId(user.getId());
			order.setBuyerNick(user.getUsername());
			CommonResult result = this.orderService.createOrder(order);
			return ResponseEntity.status(HttpStatus.CREATED).body(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
	@GetMapping("success")
	public String success(@RequestParam("id")String orderId, Model model){
		
		Order order = this.orderService.queryOrderById(orderId);
		model.addAttribute("order", order);
		
		model.addAttribute("date", new DateTime().plusDays(2).toString("MM月dd日"));
		
		return "success";
	}
	
	@GetMapping("create")
	public String toCartOrder(Model model){
		
		List<Cart> cartList = this.cartService.queryCartList();
		
		model.addAttribute("carts", cartList);
		
		return "order-cart";
	}

}
